# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution(object):
    def __init__(self):
        self.sum = 0

    def hasPathSum(self, root, targetSum):
        """
        :type root: Optional[TreeNode]
        :type targetSum: int
        :rtype: bool
        """
        self.targetSum = targetSum
        if not root:
            return False

        if self.loop(root) is True:
            return True
        else:
            return False

    def loop(self, node):
        self.sum += node.val

        if not node.left and not node.right:
            if self.sum == self.targetSum:
                return True
            else:
                return

        if node.left:
            if self.loop(node.left):
                return True
            self.sum -= node.left.val

        if node.right:
            if self.loop(node.right):
                return True
            self.sum -= node.right.val
